<template>
<j-modal
    :title="title"
    :width="width"
    :visible="visible"
    switchFullscreen
    @ok="handleOk"
    :okButtonProps="{ class:{'jee-hidden': disableSubmit} }"
    @cancel="handleCancel"
    cancelText="关闭">
 <!-- <a-modal title="地图选点" :visible="visible" @ok="handleOk" @cancel="handleCancel"> -->
    <div class="search-box">
      <a-input v-model="searchText" placeholder="输入地址关键词" />
      <a-button type="primary" @click="handleSearch">搜索</a-button>
    </div>
    <div id="tdt-map-container" style="height: 500px; margin-top: 16px"></div>
  </j-modal>
</template>

<script>
export default {
  data() {
    return {
      title:'',
      width:800,
      visible: false,
      disableSubmit: false,
      searchText: '',
      map: null,
      marker: null,
      currentPos: { lng: 116.40, lat: 39.90 } // 默认坐标
    };
  },
  methods: {
     show(model){
      this.searchlocation = [];
      console.log("selectedPoint:",JSON.stringify(model));
      this.initMap();
    },
    initMap() {
      this.map = new T.Map('tdt-map-container');
      this.map.centerAndZoom(new T.LngLat(this.currentPos.lng, this.currentPos.lat), 12);
      
      // 添加点击事件监听
      this.map.addEventListener('click', this.handleMapClick);
    },
    handleSearch() {
      const geocoder = new T.Geocoder();
      geocoder.getPoint(this.searchText, (result) => {
        if (result.point) {
          this.map.centerAndZoom(new T.LngLat(result.point.lng, result.point.lat), 16);
          this.addMarker(result.point);
        }
      }, '北京市'); // 可指定搜索范围城市
    },
    addMarker(point) {
      const T = window.T;
      if (this.marker) this.map.removeOverLay(this.marker);
      
      this.marker = new T.Marker(new T.LngLat(point.lng, point.lat), {
        icon: new T.Icon({
          iconUrl: 'https://api.tianditu.gov.cn/img/map/marker.png',
          iconSize: new T.Point(25, 34)
        })
      });
      this.map.addOverLay(this.marker);
    },
    handleMapClick(e) {
      const T = window.T;
      const lnglat = e.lnglat;
      this.currentPos = { lng: lnglat.lng, lat: lnglat.lat };
      this.addMarker(lnglat);
      
      // 反向解析地址
      new T.Geocoder().getLocation(
        new T.LngLat(lnglat.lng, lnglat.lat),
        (result) => {
          this.searchText = result.address; 
        }
      );
    },
    handleCancel () {
      this.close()
    },
    close () {
      this.$emit('close');
      this.visible = false;
    },
    handleOk() {
      this.$emit('select', {
        lng: this.currentPos.lng,
        lat: this.currentPos.lat,
        address: this.searchText
      });
      this.visible = false;
    }
  }
};
</script>